// pages/dynamicDetail/dynamicDetail.js
const http = require('../../utils/http.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    itemList: ['举报', '回复'],
    autoFocus: false,
    details:{},
    conmentText:'',
    replyList:[],
    connectemojiO: ['😊', '😅', '😲', '😭', '😂', '😄', '😩', '😞', '😵', '😒', '😍',
      '😤', '😜', '😝', '😋', '😘', '😚', '😷', '😳', '😃', '😆', '😁', '😢', '😨',
      '😠', '😣', '😌', '😖', '😔', '😰', '😱', '😪', '😏', '😓', '🍊', '🍈', '🌰', '🍌', '🍉','🍆'
    ],
    isShow: false,//控制emoji表情是否显示
    keyHeight:''
  },

  emojiShowHide(){
    this.setData({
      isShow:true,
      // autoFocus:true
    })
  },

  pullKeyboard(){
    this.setData({
      isShow: false,
      autoFocus: true
    })
  },

  //个人信息中心
  toHomepage1(e) {
    var eid = e.currentTarget.dataset.eid;
    wx.navigateTo({
      url: '/pages/toPersonal/toPersonal?eid=' + eid
    })
  },
  //展开评论详情
  commentDetail(e){
    var item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: "/pages/commentDetail/commentDetail?item=" + JSON.stringify(item)
    })
  },
  //图片预览
  previewImg(e) {
    var imgs = e.currentTarget.dataset.imgs,
      img = e.currentTarget.dataset.img;
    console.log(imgs, img)
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  //点赞
  handleZan(e) {
    var pid = e.currentTarget.dataset.id;
    var uid = app.globalData.uid;
    var current = this.data.current;
    var isZan = e.currentTarget.dataset.zan;
    if (isZan == 1) {
      return wx.showToast({
        title: '您已点过赞了',
        icon: 'none'
      })

    }
    http.fetchApi('procedure_t', { p: `R2017002|${pid}|${uid}` }).then(res => {
      if (res.data.code == 1) {
        if (res.data.results[0].codes == 1) {
          wx.showToast({
            title: '点赞成功',
            icon: 'none'
          })
          var details = this.data.details;
          details.like_num++;
          details.sfdz = 1;
          this.setData({
            details
          })

          //更新列表页的数据
          var pages = getCurrentPages();
          //上一个页面实例对象
          var prePage = pages[pages.length - 2];
          if (this.data.shared == 0) {
            if (prePage.route == "pages/community/community") {
              prePage.getHotDynamic(1, this.data.type);
            }
          }
         
         

        }
      } else {
        wx.showToast({
          title: '网络繁忙',
          icon: 'none'
        })
      }
    })
  },

  //举报回复
  report(e) {
    var itemList = this.data.itemList;
    var rid=e.currentTarget.dataset.rid;
    var item=e.currentTarget.dataset.item;
    console.log(item)
    wx.showActionSheet({
      itemList,
      itemColor: '#1478F6',
      success: (res) => {
        if (res.tapIndex == 0) {
          wx.navigateTo({
            url: "/pages/report/report?reportType=2&typeId=" + item.id + '&h_uid=' + item.uid
          })
        } else {
          
          wx.navigateTo({
            url: "/pages/commentDetail/commentDetail?item=" + JSON.stringify(item)
          })
          // this.setData({
          //   autoFocus: true
          // })
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
//回复 评论
  handleComment(){
    
    var post_id=this.data.pid;
    var user_id = app.globalData.uid;
    var conment_content = this.data.conmentText;
    if (!conment_content){
      wx.showToast({ title: '内容不能为空', icon: 'none' });
      return
    }
    http.fetchApi('p_huifu_tz', { p: `R2017008|${post_id}|${user_id}|1|0|0|${conment_content}` }).then(res => {
     console.log(`R2017008|${post_id}|${user_id}|1|0|0|${conment_content}`)
      if (res.data.code == 1) {
        if (res.data.results[0].codes == 1) {
          wx.showToast({ title: '评论成功' });
          this.setData({
            conmentText:''
          })
          this.getDetails();

          //更新列表页的数据
          var pages = getCurrentPages();
          //上一个页面实例对象
          var prePage = pages[pages.length - 2];
          if (this.data.shared == 0){
            if (prePage.route == "pages/community/community") {
              prePage.getHotDynamic(1, this.data.type);
            }
          }
         

        }else{
          wx.showToast({ title: '网络繁忙',icon:'none' });
        }
      } else if (res.data.code == 0){
        wx.showToast({ title: res.data.results, icon: 'none' });
      }
    })
  },
  pinglun(){
    this.setData({
      autoFocus: true
    })
  },
  conmentContent(e){
    var conmentText = e.detail.value;
    this.setData({
      conmentText
    })
  },

  //关注
  addFollow(){
    var uid = app.globalData.uid;
    var p_uid = this.data.details.p_uid
    http.fetchApi('procedure_t', { p: `R2017010|${uid}|${p_uid}` }).then(res=>{
      if(res.data.code==1){
        if(res.data.results[0].codes==1){
          wx.showToast({
            title: '已关注'
          })
          this.getDetails();
        } else if (res.data.results[0].codes == 0){
          wx.showToast({title: '不能关注自己!',icon:'none'})
        }
      }
    })
  },

  //个人信息中心
  toHomepage() {
    wx.navigateTo({
      url: '/pages/toPersonal/toPersonal?eid=' + this.data.details.p_uid
    })
  },

  //每进入一次增加一次浏览量
  addVolume(pid){
   http.fetchApi('procedure_t', { p: `R2017004|${pid}` })
  },

  //获取详情
  getDetails(){
    var uid = app.globalData.uid;
    http.fetchApi('procedure_t', { p: `R2019003|${uid}|${this.data.pid}` }).then(res=>{
      console.log(`R2019003|${uid}|${this.data.pid}`)
      if(res.data.code==1){
        var details = res.data.results[0];
        this.setData({
          details
        })

        this.getReplyList()
      }else{
        wx.showToast({
          title: '网络繁忙',
          icon:''
        })
      }
    })
  },

  //帖子回复列表
  getReplyList(){
    http.fetchApi('procedure_t', { p: `R2019008|${this.data.pid}` }).then(res=>{
      if(res.data.code==1){
        var replyList = res.data.results;
        
        this.setData({
          replyList
        })
      }
    })
  },

  emoji2Str(str) {

    return unescape(escape(str).replace(/\%uD.{3}/g, ''));

  },

  //获取键盘高度
  getKeyHeight(e){
    console.log(e.detail.height)
    this.setData({
      keyHeight: e.detail.height
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   // console.log(options.focus)
   this.setData({
     pid:options.pid,
     type: options.type || 1,
     shared:options.shared || 0
   })
   console.log(this.data.shared)
    this.addVolume(options.pid);

    // 分享进来时获取uid
    if (app.globalData.uid){
      this.getDetails();
    }else{
      wx.getSetting({
        success:(res)=> {
          if (!res.authSetting['scope.userInfo']) {
            wx.showModal({
              title: '提示',
              content: '您还没有授权,请开启授权',
              confirmColor:'#0DCF92',
              success(ret) {
                if (ret.confirm) {
                  wx.reLaunch({
                    url: '/pages/index/index',
                  })
                } else if (ret.cancel) {
                  
                }
              }
            })
           
          }else{
            wx.getUserInfo({
              success: results => {
                app.globalData.userInfo = results.userInfo
                console.log(app.globalData.userInfo);

                wx.login({
                  success: (res2) => {

                    if (res2.code) {
                      var url;
                      const yxhj = wx.getSystemInfoSync();
                      console.log(yxhj.AppPlatform)
                      app.globalData.cj = yxhj.AppPlatform
                      if (yxhj.AppPlatform == 'qq') {
                        url = app.globalData.host + 'qqApi/login'
                      } else {
                        url = app.globalData.host + 'api/login'
                      }
                      wx.request({
                        url,
                        method: 'get',
                        header: {
                          "Content-Type": "applciation/json"
                        },
                        // data: { encryptedData: results.encryptedData, iv: results.iv, code: res.code },
                        data: { avatarUrl: results.userInfo.avatarUrl, nickName: this.emoji2Str(results.userInfo.nickName), code: res2.code },
                        success: (result) => {
                          if (result.data.code == 1) {
                           
                            app.globalData.token = result.data.accesstoken;
                            //uid保存全局
                            app.globalData.uid = result.data.uid;            
                            this.getDetails();
                          } else {
                            wx.showToast({
                              title: '网络繁忙',
                              icon:'none'
                            })
                           
                          }

                        }
                      })


                    } else {
                      console.log('网络繁忙' + res.errMsg)
                    }
                  }
                })

              }
            })
          }
        }
      })
    }
   

    if (options.focus){
      this.setData({
        autoFocus: options.focus
      })
    }
    
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      var pid = res.target.dataset.id;
      var uid = app.globalData.uid;
      http.fetchApi('procedure_t', { p: `R2017005|${pid}|${uid}` }).then(req => {
        if (req.data.code == 1) {
          if (req.data.results[0].codes == 1) {
            var details = this.data.details;
            details.fenxiang_num++;
            this.setData({
              details
            })

            //更新列表页的数据
            var pages = getCurrentPages();
            //上一个页面实例对象
            var prePage = pages[pages.length - 2];
           
           if(this.data.shared==0){
             if (prePage.route == "pages/community/community") {
               prePage.getHotDynamic(1, this.data.type);
             }
           }
           
            
          }
        }
      })
    }
    return {
      // title: '自定义转发标题',
      path: '/pages/dynamicDetail/dynamicDetail?type=1&pid=' + pid +'&shared=1'
    }
  }
})